package org.spring.qq_chat_java.controller;



import com.aliyun.oss.OSS;

import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;

import org.spring.qq_chat_java.constant.oss;
import org.spring.qq_chat_java.pojo.Result;

import org.spring.qq_chat_java.utils.OssUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/files")
@CrossOrigin(origins = "*")
public class FileController {

    // 生成上传凭证
     @GetMapping("/policy")
    public Result<Map<String,String>> policy (){
        String endpoint = oss.endpoint;
        String OSSAccessKeyId = oss.OSSAccessKeyId;
        String accessSecret = oss.accessSecret;
        String bucket =oss.bucket;
        String host ="https://"+ bucket+"."+endpoint;

        //指定文件夹前缀
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dir= simpleDateFormat.format(new Date())+"/";
        //创建oss实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, OSSAccessKeyId,accessSecret);

        try{
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis()+expireTime*1000;
            Date expiration = new Date(expireEndTime);
            // 设置上传策略： 禁止覆盖同名文件， 只允许更新
            PolicyConditions policyConds=new PolicyConditions();
            // 设置上传大小限制
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE,0,1048576000);
            policyConds.addConditionItem(MatchMode.StartWith,PolicyConditions.COND_KEY,dir);


            String postPolicy = ossClient.generatePostPolicy(expiration,policyConds);
            byte[] binaryData= postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String,String> resMap=new LinkedHashMap<String,String>();
            resMap.put( "OSSAccessKeyId",OSSAccessKeyId);
            resMap.put("policy",encodedPolicy);
            resMap.put("Signature",postSignature);
            resMap.put("dir",dir);
            resMap.put("host",host);
            resMap.put("expire",String.valueOf(expireEndTime/1000));

            return Result.success(resMap);

        }catch (Exception e){
            System.out.println(e);
        } finally {
            //关闭OSSClient
             ossClient.shutdown();
        }

       return Result.error("上传失败");
    }

    //获取文件的url地址
     @GetMapping("/getUrl")
     public Result<String> getUrl(String fileName){
        try{
            String url = OssUtils.buildAliyunSTSCredentials(fileName);
            return  Result.success(url);
        }  catch (Exception e){
              return Result.error("获取文件地址失败");
        }

     }



}
